package cn.ldh.filters;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {

        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();

        String uri = request.getRequestURI();

        if(uri.endsWith("/login ") || uri.endsWith("/register ")
                || uri.contains("/static/") ){
            return false;
        }


        return true;
    }

    @Override
    public Object run() throws ZuulException {

        // 1 获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();

        // 2 获取响应对象
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();

        // 3 获取请求头中的 token
        String token = request.getHeader("token");

        //3.如果没有token，登录检查失败 ，
        if (StringUtils.isEmpty(token)){

            HashMap<String, Object> map = new HashMap<>();

            map.put("success","false");
            map.put("message","nologin");

            // 设置中文编码集
            response.setContentType("application/json;charset=utf-8");


            //把map转成json字符串，写到浏览器
            String jsonString = JSON.toJSONString(map);

            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

            try {
                response.getWriter().println(jsonString);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //3.2.阻止filter继续往后执行
            RequestContext.getCurrentContext().setSendZuulResponse(false);

        }



        return null;
    }
}
